<?php

class Jhg_TwigExtention_Meta extends Twig_Extension {

    const LINK_TYPE_CSS = 1;
    const LINK_TYPE_JS = 2;

    private $_css = array();
    private $_js = array();
    private $_cssPattern = '<link href="%s" rel="stylesheet" type="text/css" />';
    private $_jsPattern = '<script type="text/javascript" src="%s"></script>';

    public function getName() {
        return 'jh_core';
    }

    public function getFunctions() {
        return array(
            'var_export' => new Twig_Function_Function('var_export'),
            'css' => new Twig_Function_Method($this, 'getCss'),
            'js' => new Twig_Function_Method($this, 'getJs'),
        );
    }

    public function getFilters() {
        return array(
            'stripslashes' => new Twig_Filter_Function('stripslashes'),
            'debug' => new Twig_Filter_Method($this, 'filterDebug'),
            'truncate' => new Twig_Filter_Method($this, 'filterTruncate'),
        );
    }

    public function getCss($link) {
        return $this->addLink($link, self::LINK_TYPE_CSS);
    }

    public function getJs($local, $remote = null) {
        $link = ('development' !== APPLICATION_ENV && NULL !== $remote) ? $remote : $local;
        return $this->addLink($link, self::LINK_TYPE_JS);
    }

    public function filterDebug($var) {
        return Zend_Debug::dump($var, null, false);
    }

    public function filterTruncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) {
        if ($length == 0)
            return '';

        if (strlen($string) > $length) {
            $length -= min($length, strlen($etc));
            if (!$break_words && !$middle) {
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
            }
            if (!$middle) {
                return substr($string, 0, $length) . $etc;
            } else {
                return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2);
            }
        } else {
            return $string;
        }
    }

    private function addLink($link, $type) {
        if (is_array($link)) {
            $res = array();
            foreach ($link as $l) {
                $res[] = $this->addLinkFile($l, $type);
            }
            return join(PHP_EOL, $res);
        } else {
            return $this->addLinkFile($link, $type);
        }
    }

    private function addLinkFile($file, $type) {
        $arr = null;
        $pattern = '';
        if (self::LINK_TYPE_CSS === $type) {
            $arr = & $this->_css;
            $pattern = $this->_cssPattern;
        } else if (self::LINK_TYPE_JS === $type) {
            $arr = & $this->_js;
            $pattern = $this->_jsPattern;
        }
        if (null !== $arr) {
            if (!in_array($file, $arr)) {
                $arr[] = $file;
                return sprintf($pattern, $file);
            }
        }
        return false;
    }

}